package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zxw
 * @date 2024/11/19 13:15
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryTreeNode(String id) {
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (k1, k2) -> k2));

        List<CourseCategoryTreeDto> categoryTreeDtos = new ArrayList<>();

        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            if(item.getParentid().equals(id)){
                categoryTreeDtos.add(item);
            }
            CourseCategoryTreeDto parentCategoryTree = mapTemp.get(item.getParentid());
            if(parentCategoryTree!=null){
                if(parentCategoryTree.getChildrenTreeNodes()==null){
                    parentCategoryTree.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>()) ;
                }
                parentCategoryTree.getChildrenTreeNodes().add(item);
            }
        });
        return categoryTreeDtos;
    }
}
